package com.vaadin.pekka.treegridwidget;

import java.util.Map;

import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.PaintTarget;
import com.vaadin.ui.AbstractComponent;

/**
 * Server side component for the VTreeGrid widget.
 */
@com.vaadin.ui.ClientWidget(com.vaadin.pekka.treegridwidget.client.ui.VTreeGrid.class)
public class TreeGrid extends AbstractComponent {

    public enum UpdateMode {
        ALL
    }

    private UpdateMode updateMode = UpdateMode.ALL;

    private String[][] columnHeaders = {};
    private String[][] rowHeaders = {};
    private String[][] data = {};

    private void paintColumnHeaders(final PaintTarget target)
            throws PaintException {
        int i = 0;
        String attr;
        target.addAttribute("columnlevels", columnHeaders.length);
        for (String[] array : columnHeaders) {
            attr = "ch" + i;
            target.addAttribute(attr, array);
            i++;
        }
    }

    private void paintRowHeaders(final PaintTarget target)
            throws PaintException {
        int i = 0;
        String attr;
        target.addAttribute("rowlevels", rowHeaders.length);
        for (String[] array : rowHeaders) {
            attr = "rh" + i;
            target.addAttribute(attr, array);
            i++;
        }
    }

    private void paintData(final PaintTarget target) throws PaintException {
        int i = 0;
        for (String[] array : data) {
            target.addAttribute("cd" + i, array);
            i++;
        }
    }

    @Override
    public void paintContent(PaintTarget target) throws PaintException {
        super.paintContent(target);

        target.addAttribute("updatemode", updateMode.ordinal());
        if (updateMode == UpdateMode.ALL) {
            paintColumnHeaders(target);
            paintRowHeaders(target);
            paintData(target);
        }
    }

    public void setGridData(String[][] columnHeaders, String[][] rowHeaders,
            String[][] dataByColumns) {
        this.columnHeaders = columnHeaders;
        this.rowHeaders = rowHeaders;
        data = dataByColumns;
        requestRepaint();
    }

    /**
     * Receive and handle events and other variable changes from the client.
     * 
     * {@inheritDoc}
     */
    @Override
    public void changeVariables(Object source, Map<String, Object> variables) {
        super.changeVariables(source, variables);

        // Variables set by the widget are returned in the "variables" map.

        if (variables.containsKey("click")) {

            // When the user has clicked the component we increase the
            // click count, update the message and request a repaint so
            // the changes are sent back to the client.

            requestRepaint();
        }
    }

}
